﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Entities.Content;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Content.Common;
namespace DotNetNuke.Modules.mytargetmodule.Components.Taxanomy
{
    public class Content
    {
        private const string ContentTypeName = "TaskMangaerTask";

        public ContentItem CreateContentItem(Task objtask, int TabId)
        {
            var typeController = new ContentTypeController();
            var colContentType= (from t in typeController.GetContentTypes() where t.ContentType == ContentTypeName select t) ;
            int contentTypeID;
 
           if (colContentType.Count() > 0)
           {
            var contentType = colContentType.Single();
            contentTypeID = contentType == null ? CreateContentType() : contentType.ContentTypeId;                //CreateContentType() : contentType.ContentTypeId;
           } 
           else
           {
               contentTypeID = CreateContentType();
           }

           var objContent = new ContentItem
           {
               Content = objtask.Taskname + "" + objtask.TaskDescription,
               ContentTypeId = contentTypeID,
               Indexed = false,
               ContentKey = "tid=" + objtask.TaskID,
               ModuleID = -1,
               TabID = TabId
           };
           objtask.ContentItemId = Util.GetContentController().AddContentItem(objContent);

           var cntTerm = new Term();
           cntTerm.ManageTestTerms(objtask, objContent);

           return objContent;
       }

        internal void DeleteContentItem(int contentItemID)
        {
            if (contentItemID <= Null.NullInteger) return;
            var objContent = Util.GetContentController().GetContentItem(contentItemID);
            if (objContent == null) return;

            // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?)
            //var cntTerms = new Terms();
            //cntTerms.RemoveQuestionTerms(objContent);

            Util.GetContentController().DeleteContentItem(objContent);
        }

        private static int  CreateContentType()
        {
            var typeController = new ContentTypeController();
            var objContentType = new ContentType { ContentType = ContentTypeName };

            return typeController.AddContentType(objContentType);
        }  
    }
}